<template>
  <div>
    <!-- 搜索栏 -->
     <div style="display: flex;margin-top: 20px; margin-bottom: 20px; margin-left: 10px">
      <el-input
        v-model="searchTitle"
        placeholder="请输入申请标题搜索"
        clearable
      ></el-input>
      <el-button type="warning" style="margin-left: 10px; margin-right: 10px" @click="searchApplication" circle><el-icon><Search /></el-icon></el-button>
    </div>

    <!-- 申请列表 -->
    <el-table :data="applicationList" style="width: 100%; margin-left: 10px">
      <el-table-column prop="aid" label="申请编号"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="createdDate" label="创建日期"></el-table-column>
      <el-table-column prop="submittedDate" label="提交日期"></el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column prop="handler" label="处理人"></el-table-column>
      <el-table-column label="操作" width="250px">
        <template v-slot="scope">
          <el-popover
            popper-class="descriptionPop"
            placement="bottom"
            :title="scope.row.title" 
            :width="300"
            trigger="click"
            :content="scope.row.description" 
          >
            <template #reference>
              <el-button type="warning" size="small" @click="handleDescription(scope.row)" text>描述</el-button>
            </template>
          </el-popover>
          <el-button type="warning" size="small" @click="handleDownload(scope.row)" text>下载</el-button>
          <el-button type="warning" size="small" @click="handleModify(scope.row)" text>修改</el-button>
          <el-button type="warning" size="small" @click="handleDelete(scope.row)" text>删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="applicationList.length === 0 && isSearch === true " style="text-align: center; margin-top: 100px;">
      无匹配申请
    </div>
  </div>
</template>

<script>
import { Search } from '@element-plus/icons-vue'

export default {
  components: {
    Search,
  },
  data() {
    return {
      searchTitle: '',
      applicationList: [
      //{ aid: '001', title: '申请1', createdDate: '2024-07-09', submittedDate: '2024-07-10', status: '处理中', handler: '张三' },
      //{ aid: '002', title: '申请2', createdDate: '2024-07-09', submittedDate: '2024-07-10', status: '已完成', handler: '李四' },
      ],
      isSearch: false,
    }
  },
  mounted() {
    this.fetchApplications()
  },
  methods: {
    fetchApplications() {
      console.log(sessionStorage.getItem('userInfo'))
      this.axios.get(`https://apifoxmock.com/m1/4767131-4420546-default/api/get_applications`/* http://127.0.0.1:5000/application/check_application */,
       { params: {email:sessionStorage.getItem('userInfo'), title:this.searchName} })
      .then(response => {
        if (Array.isArray(response.data.application)) {
           console.log("Result data is an array:", response.data.application)
          this.applicationList = response.data.application; // 确保 data 是数组
        } else {
          this.applicationList = []; // 如果没有匹配结果，清空 applicationList
          console.error('Error: Expected an array but got:', response.data.application)
        }
      })
      .catch(error => {
        this.applicationList = []; // 请求出错时也清空 applicationList
        console.error('Error searching applicationList:', error)
      });
    },
    searchApplication() {
      this.fetchApplications()
      this.isSearch = true
    },
    handleDescription(row) {
      // 处理描述操作
      // 使用 axios 获取描述内容
      this.axios.get(`https://apifoxmock.com/m1/4767131-4420546-default/api/get_application_description`/* http://your-api-url/applications/${row.applicationId}/description */,
      { params: { aid:this.aid} })
      .then(response => {
        row.description = response.data.description; // 假设响应数据为描述内容
      })
      .catch(error => {
        console.error('Error fetching description:', error)
        row.description = '无'
      });
    },
    handleDownload(row) {
      // 处理下载操作
      const fileName = row.title + '.txt'
      const fileUrl = '/path/to/' + fileName // 文件的URL地址
      this.axios.get(fileUrl, { responseType: 'blob' })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
      })
      .catch(error => {
        console.error(error)
      })
    },
    handleModify(row) {
      if(row.status !== 'false') { //暂定用false代替未提交
        this.$message({
              message: '当前为不可修改状态！',
              type: "warning",
            })
      } else {
        const info = row.aid // 需要传递给draft-application的信息
        console.log('chile.application:'+info)
        this.$emit('goToSubmitApplication', info) // 触发父组件的 goToSubmitApplication 方法，传递信息
      }
    },
    handleDelete(row) {
      // 处理删除操作
      if(row.status !== 'false') { //暂定用false代替未提交
        this.$message({
              message: '当前为不可删除状态！',
              type: "warning",
            })
      } else {
        this.axios.post('https://apifoxmock.com/m1/4767131-4420546-default/api/application_delete',
        {aid:row.aid})
        .then(response => {
          if(response.status === 200){
            this.$message({
              message: '删除成功！',
              type: "success",
            })
          }
          else {
            this.$message({
              message: '删除失败！',
              type: "warning",
            })
          }
        })
      }
    },
  },
}
</script>

<style scoped>
button {
padding-left:0px;
}
</style>
